package com.zhuhjay.common.utils;

import com.zhuhjay.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * 文件上传下载的工具类
 * @author ZhuHJay
 * @date 2022/3/24 19:22
 */
@Slf4j
public class FileLoadUtils {

    public static String fileUpload(MultipartFile file, String uploadPath, String[] types){
        // 判断文件类型是否匹配
        String suf = Objects.requireNonNull(file.getOriginalFilename())
                .substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        log.warn("上传文件的类型为: {}", suf);
        log.warn("上传路径为: {}", uploadPath);
        boolean isPass = false;
        for (String type : types) {
            if( type.equalsIgnoreCase(suf) ){
                isPass = true;
                break;
            }
        }
        if( !isPass ){
            throw new CustomException("上传文件的类型不匹配");
        }
        String fileName = UuidUtils.getUuid() + suf + "." + suf;
        try {
            file.transferTo(new File(uploadPath + "/" + fileName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("修改失败, 请重试");
        }
        return fileName;
    }

}
